package com.example.hello.controller;

import com.example.hello.common.Result;
import com.example.hello.dto.AttractionDTO;
import com.example.hello.entity.Attraction;
import com.example.hello.security.UserDetailsServiceImpl;
import com.example.hello.service.AttractionService;
import com.example.hello.service.FileStorageService;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/attraction")
@Tag(name = "景点管理", description = "景点信息管理相关接口")
public class AttractionController {

    private static final Logger logger = LoggerFactory.getLogger(AttractionController.class);

    @Autowired
    private AttractionService attractionService;
    
    @Autowired
    private FileStorageService fileStorageService;
    
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @PostMapping("/add")
    @PreAuthorize("hasAnyRole('ADMIN', 'EDITOR')")
    @Operation(summary = "添加景点", description = "添加新的景点信息", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "添加成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> addAttraction(@RequestBody AttractionDTO attractionDTO) {
        try {
            // 获取当前登录用户ID
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            Long userId = userDetailsService.getUserIdByUsername(userDetails.getUsername());
            
            // 设置创建者ID
            attractionDTO.setCreatedBy(userId);
            
            // 设置初始状态为待审核
            if (attractionDTO.getStatus() == null) {
                attractionDTO.setStatus(0);
            }
            
            boolean success = attractionService.addAttraction(attractionDTO, userId);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyRole('ADMIN', 'EDITOR')")
    @Operation(summary = "更新景点信息", description = "更新已有的景点信息", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> updateAttraction(@RequestBody AttractionDTO attractionDTO) {
        try {
            return Result.success(attractionService.updateAttraction(attractionDTO));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    @PostMapping("/delete/{attractionId}")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(summary = "删除景点", description = "删除指定的景点信息", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> deleteAttraction(
            @Parameter(description = "景点ID", required = true) 
            @PathVariable Long attractionId) {
        try {
            return Result.success(attractionService.deleteAttraction(attractionId));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    @GetMapping("/detail/{attractionId}")
    @Operation(summary = "获取景点详情", description = "获取指定景点的详细信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "景点不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Attraction> getAttractionDetail(
            @Parameter(description = "景点ID", required = true) 
            @PathVariable Long attractionId) {
        try {
            // 增加浏览量
            attractionService.incrementViewCount(attractionId);
            
            Attraction attraction = attractionService.getAttractionById(attractionId);
            if (attraction == null) {
                return Result.error(404, "景点不存在");
            }
            return Result.success(attraction);
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    @GetMapping("/list")
    @Operation(summary = "获取景点列表", description = "分页获取景点列表，可根据条件筛选")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<PageInfo<Attraction>> getAttractionList(
            @Parameter(description = "景点名称") 
            @RequestParam(required = false) String name,
            @Parameter(description = "分类ID") 
            @RequestParam(required = false) Integer categoryId,
            @Parameter(description = "标签") 
            @RequestParam(required = false) String tag,
            @Parameter(description = "状态(0-待审核 1-正常 2-下架)") 
            @RequestParam(required = false) Integer status,
            @Parameter(description = "页码") 
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") 
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Attraction attraction = new Attraction();
            attraction.setName(name);
            attraction.setCategoryId(categoryId);
            
            if (tag != null && !tag.isEmpty()) {
                List<String> tags = new ArrayList<>();
                tags.add(tag);
                attraction.setTags(tags);
            }
            
            PageInfo<Attraction> pageInfo = attractionService.getAttractionList(attraction, pageNum, pageSize);
            return Result.success(pageInfo);
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    @PostMapping("/upload/cover")
    @PreAuthorize("hasAnyRole('ADMIN', 'EDITOR')")
    @Operation(summary = "上传景点封面图", description = "上传景点封面", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "上传成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<List<String>> uploadCoverImages(@RequestParam("files") MultipartFile[] files) {
        try {
            // 验证文件
            if (files == null || files.length == 0) {
                return Result.error(400, "请选择至少一个文件上传");
            }
            
            // 验证文件类型
            for (MultipartFile file : files) {
                String contentType = file.getContentType();
                if (contentType == null || !contentType.startsWith("image/")) {
                    return Result.error(400, "只能上传图片文件");
                }
            }
            
            // 上传文件
            List<String> urls = new ArrayList<>();
            for (MultipartFile file : files) {
                String url = fileStorageService.uploadFile(file, "attraction/cover");
                urls.add(url);
            }
            
            return Result.success(urls);
        } catch (Exception e) {
            logger.error("上传景点封面图失败", e);
            return Result.error(500, "文件上传失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/upload/gallery")
    @PreAuthorize("hasAnyRole('ADMIN', 'EDITOR')")
    @Operation(summary = "上传景点图片集", description = "上传景点图片集", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "上传成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<List<String>> uploadGalleryImages(@RequestParam("files") MultipartFile[] files) {
        try {
            // 验证文件
            if (files == null || files.length == 0) {
                return Result.error(400, "请选择至少一个文件上传");
            }
            
            // 验证文件类型
            for (MultipartFile file : files) {
                String contentType = file.getContentType();
                if (contentType == null || !contentType.startsWith("image/")) {
                    return Result.error(400, "只能上传图片文件");
                }
            }
            
            // 上传文件
            List<String> urls = new ArrayList<>();
            for (MultipartFile file : files) {
                String url = fileStorageService.uploadFile(file, "attraction/gallery");
                urls.add(url);
            }
            
            return Result.success(urls);
        } catch (Exception e) {
            logger.error("上传景点图片集失败", e);
            return Result.error(500, "文件上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/status/{attractionId}/{status}")
    @PreAuthorize("hasRole('ADMIN')")
    @Operation(summary = "修改景点状态", description = "修改景点的状态", 
            security = @SecurityRequirement(name = "JWT"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "修改成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> updateAttractionStatus(
            @Parameter(description = "景点ID", required = true) 
            @PathVariable Long attractionId,
            @Parameter(description = "状态(0-待审核 1-正常 2-下架)", required = true) 
            @PathVariable Integer status) {
        try {
            AttractionDTO attractionDTO = new AttractionDTO();
            attractionDTO.setAttractionId(attractionId);
            attractionDTO.setStatus(status);
            
            return Result.success(attractionService.updateAttraction(attractionDTO));
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }
} 